<template>
  <!-- 广告管理 -->
  <div>
    <!-- 搜索 -->
    <div>
      <el-space>
        <el-select v-model="input.status" placeholder="请选择广告状态">
          <li v-for="(item, index) in adStatusMap" :key="index">
            <el-option :label="item.name" :value="item.value" />
          </li>
        </el-select>
        <el-select v-model="input.type" placeholder="请选择广告类型">
          <li v-for="(item, index) in adTypeMap" :key="index">
            <el-option :label="item.name" :value="item.value" />
          </li>
        </el-select>

        <el-button type="primary" @click="sous()">
          <span class="iconfont icon-icon-sousuo" style="margin-right: 10px"></span>查找
        </el-button>

        <!-- 添加对话框 -->
        <el-button type="text">
          <el-button type="primary" @click="addtan">
            <span class="iconfont icon-icon-B-tianjiabiji" style="margin-right: 10px"></span>添加
          </el-button>
        </el-button>

        <el-button type="primary" @click="reset()">刷新</el-button>
      </el-space>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column label="广告ID" prop="id" width="120" align="center" />
      <el-table-column label="广告标题" prop="title" align="center" />
      <el-table-column label="广告图片" align="center">
        <template #default="scope">
          <el-popover placement="right" v-if="scope.row.imgUrl && scope.row.type != 6 && scope.row.type != 9">
            <template #reference>
              <el-image style="width: 80px" :src="scope.row.imgUrl" />
            </template>
            <el-image :src="scope.row.imgUrl" />
          </el-popover>
          <el-tag v-else type="info">类型无需图片</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="广告类型" width="180" align="center">
        <template #default="scope">
          <el-tag>{{forwide(scope.row.type) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="广告状态" width="180" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status?'success':'danger'" plain>{{ scope.row.status==1?'激活':'冻结' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="关联类型" width="180" align="center">
        <template #default="scope">
          <el-tag>{{fortype(scope.row.unionType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="关联值[ID]" prop="unionValue" align="center" />
      <el-table-column label="创建时间" prop="gmtCreate" width="180" align="center">
        <template #default="scope">
          <span>{{ time(scope.row.gmtCreate)}}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="text" @click="dialogVisible = true">
            <!-- 修改按钮 -->
            <el-button size="small" type="primary" @click="amendnew ( scope.row)">编辑</el-button>
          </el-button>
          <!-- 激活 -->
          <el-button size="small" type="danger" @click="handleDelete( scope.row)">删除</el-button>
          <!-- 对话框 -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="600px" :before-close="handleClose">
      <!-- 内容 -->
      <el-form :inline="true" :model="addr" :rules="rules" ref="formName" class="demo-ruleForm" status-icon label-width="120px">
        <el-form-item label="广告标题" prop="title">
          <el-input v-model.trim="addr.title" placeholder="广告标题" />
        </el-form-item>
        <el-form-item label="广告类型" prop="type">
          <el-select v-model="addr.type" placeholder="请选择广告类型" @change="addr.unionType=''">
            <li v-for="(item, index) in adTypeMap" :key="index">
              <el-option :label="item.name" :value="item.value" />
            </li>
          </el-select>
        </el-form-item>
        <el-form-item label="广告图片" prop="imgUrl" v-if="adTypeMap[addr.type-1]?.picRequire" v-model="addr.imgUrl">
          <!-- 下标减1，从零开始，为true就显示 -->
          <el-upload class="avatar-uploader" action="http://192.168.1.188:8080/upload/admin" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="token">
            <img v-if="addr.imgUrl" :src="addr.imgUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="广告状态" style="width: 100%">
          <el-switch v-model="addr.status" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="关联类型" requried prop="unionType">
          <el-select v-model="addr.unionType" placeholder="点击时跳转目标" :disabled="!addr.type" @change="rela">
            <li v-for="(item, index) in addr.type==2?adUnionTypeMap.slice(1,2):(addr.type==9?adUnionTypeMap.slice(0,1):adUnionTypeMap)" :key="index">
              <el-option :label="item.name" :value="item.value" />
            </li>
          </el-select>
        </el-form-item>
        <el-form-item label="类目" v-if="addr.unionType == 2||addr.unionType == 1" :label="addr.unionType == 2?'类目':'商品关联'" prop="unionValue">
          <el-cascader v-model="addr.unionValue" :options="typeData" :props="props" />
        </el-form-item>
        <el-form-item label="关键字" v-if="addr.unionType==3" prop="unionValue">
          <el-input v-model="addr.unionValue" />
        </el-form-item>
        <el-form-item label="功能页面" requried v-if="addr.unionType==4" prop="unionValue">
          <el-select v-model="addr.unionValue" placeholder="请选择一个功能页面" :disabled="!addr.type">
            <li v-for="(item, index) in functionPages" :key="index">
              <el-option :label="item.name" :value="item.value" />
            </li>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetForm()">取消</el-button>
        <el-button type="primary" @click="title=='创建'? addnew() : editor()">{{title=='创建'? "新增" : "编辑"}}</el-button>
      </template>
    </el-dialog>
    <!-- 分页 -->
    <paging-vue v-bind="index" @limits="limitv" @pages="pagev"></paging-vue>
  </div>
</template>

<script>
import { post } from '@/utils/http.js' // 引入封装工具
import jsCookie from "js-cookie";
import { Plus } from '@element-plus/icons-vue'


export default {
  components: { Plus },
  data() {

    return {
      index: {
        page: 1, // 分页
        limit: 10, // 每页显示条数
        total: 10 // 总数
      },
      // 输入框
      input: {
        status: null, // 广告状态
        type: null // 广告类型
      },

      adTypeMap: [
        { value: 1, unionTypes: [1, 2, 3, 4], picRequire: true, name: '轮播' },
        { value: 2, unionTypes: [2], picRequire: true, name: '分类精选' },
        { value: 3, unionTypes: [1, 2, 3, 4], picRequire: true, name: '横幅' },
        {
          value: 4,
          unionTypes: [1, 2, 3, 4],
          picRequire: true,
          name: '首页轮播下5按钮'
        },
        { value: 6, unionTypes: [1, 2, 3, 4], picRequire: false, name: '公告' },
        { value: 9, unionTypes: [1], picRequire: false, name: '商品推荐' }
      ],
      // 4种广告关联类型
      adUnionTypeMap: [
        { value: 1, name: '商品' },
        { value: 2, name: '类目' },
        { value: 3, name: '关键字' },
        { value: 4, name: '功能页面' }
      ],
      // 广告状态
      adStatusMap: [
        { value: 0, name: '冻结' },
        { value: 1, name: '激活' }
      ],
      // 功能页面
      functionPages: [
        { value: '/pages/product/groupshop', name: '团购列表' },
        { value: '/pages/couponst', name: '优惠券列表' }
      ],

      // 弹框数据
      addr: {
        title: '', // 广告标题
        type: '', // 广告类型
        status: 0, // 广告状态
        unionType: '', // 关联类型
        imgUrl: '',//图片
        unionValue: "商品",//关联值
        color: "rgb(255,255,255)",//广告图片颜色
      },

      // 清空弹框数据
      adds: {
        title: '', // 广告标题
        type: '', // 广告类型
        status: 0, // 广告状态
        unionType: '', // 关联类型
        imgUrl: '',//图片
        unionValue: "商品",//关联值
        color: "rgb(255,255,255)",//广告图片颜色
      },
      imgs: 'https://www.baidu.com/img/flexible/logo/pc/result.png',//默认图片
      id: '',
      tableData: [], // 数据

      dialogVisible: false, // 弹出框显示/隐藏
      title: '创建',

      // 添加图片token
      token: {},
      // 关联商品数据
      typeData: [],
      // Cascader 级联选择器配置信息
      props: {
        value: "value",
        label: "label",
        children: "children",
        emitPath: false
      },

      // 表单验证
      rules: {
        title: [
          {
            required: true,
            message: "广告标题不能为空！"
          }
        ],
        type: [
          {
            required: true,
            message: "广告类型不能为空！"
          }
        ],
        unionType: [
          {
            required: true,
            message: "关联类型不能为空！"

          }
        ],
        unionValue: [
          {
            required: true,
            message: "请关联一个信息！",
          },
          {
            required: true,
            message: "选择不能为空！",
          }
        ],

      }
    }
  },

  created() {
    this.record() // 调用数据接口
  },

  methods: {
    // 时间戳
    time(value) {
      // 时间戳转换日期格式方法
      const date = new Date(value)
      const y = date.getFullYear() // 年
      const MM = date.getMonth() + 1 // 月
      const d = date.getDate() // 日
      const h = date.getHours() // 时
      const m = date.getMinutes() // 分
      const time = `${y}年${MM}月${d}日${m}分`
      return time
    },
    handleAvatarSuccess(response) {
      console.log("添加成功");
      this.addr.imgUrl = response.url;
    },
    beforeAvatarUpload() {
      console.log("添加失败");
    },
    // 关联类型改变
    rela() {
      this.addr.unionValue = ""
    },
    // 数据
    record() {
      const data = {
        _gp: 'admin.advert', // 请求参数
        _mt: 'list', // 请求参数
        type: this.input.type, // 广告类型
        status: this.input.status, // 广告状态
        pageNo: this.index.page,
        limit: this.index.limit
      }
      post(data).then((res) => {
        if (200 == res.data.errno) {
          this.tableData = res.data.data.items // 数据
          this.index.total = res.data.data.total // 分页总数
        } else {
          ElMessage.error(res.data.errmsg)
        }
      })
    },

    // 关联类型
    fortype(unionType) {
      if (1 === unionType) {
        return '商品'
      } else if (2 === unionType) {
        return '类目'
      } else if (3 === unionType) {
        return '关键字'
      } else if (4 === unionType) {
        return '功能页面'
      }
    },

    // 广告类型
    forwide(type) {
      if (4 === type) {
        return '首页轮播下5按钮'
      } else if (9 === type) {
        return '商品推荐'
      } else if (6 === type) {
        return '公告'
      } else if (2 === type) {
        return '分类精选'
      } else if (1 === type) {
        return '轮播'
      } else if (3 === type) {
        return '横幅'
      }
    },

    // 搜索
    sous() {
      this.record() // 调用数据接口
    },
    // 刷新
    reset() {
      this.input = {}
      this.record() // 调用数据接口
    },

    // 添加弹框
    addtan() {
      this.dialogVisible = false; // 弹出框显示/隐藏
      // 商品数据
      if (!this.typeData.length) {
        let data = {
          _gp: "admin.product",
          _mt: "getSpuBigTree",
        }
        post(data).then(res => {
          let { data } = res.data
          this.typeData = data
        })
      }
      Object.assign(this.addr, this.adds);
      this.title = '创建'
      this.dialogVisible = true
      this.token = { ADMINTOKEN: jsCookie.get("token") }
    },
    // 添加提交
    addnew() {
      this.$refs.formName.validate((valid) => {
        if (valid) {
          this.addr.status = 0
          if ('' == this.addr.imgUrl) {
            this.addr.imgUrl = this.imgs
          }
          const data = {
            _gp: "admin.advert",
            _mt: "create",
            ...this.addr,
          };
          post(data).then((res) => {
            if (200 == res.data.errno
            ) {
              ElMessage.success("添加成功");
              this.dialogVisible = false; // 弹出框显示/隐藏
              this.record();
            } else {
              ElMessage.error(res.data.errmsg);
            }
          });
        } else {
          ElMessage.error(`验证失败！`);
        }
      });
    },

    // 修改弹窗
    amendnew(row) {
      // 商品数据
      if (!this.typeData.length) {
        let data = {
          _gp: "admin.product",
          _mt: "getSpuBigTree",
        }
        post(data).then(res => {
          let { data } = res.data
          this.typeData = data
        })
      }
      this.title = '编辑'
      this.dialogVisible = true
      Object.assign(this.addr, row)
      this.id = row.id
    },
    // 编辑提交
    editor() {
      this.$refs.formName.validate((valid) => {
        if (valid) {
          const data = {
            _gp: 'admin.advert', // 请求参数
            _mt: 'edit', // 请求参数
            adId: this.id,
            ...this.addr
          }
          post(data).then((res) => {
            this.$refs.formName.resetFields();//清空表单验证
            if (200 == res.data.errno) {
              ElMessage.success('修改成功')
              this.dialogVisible = false
              this.record()
            } else {
              ElMessage.error(res.data.errmsg)
            }
          })
        } else {
          ElMessage.error(`验证失败！`);
        }
      });

    },
    // 删除
    handleDelete(row) {
      ElMessageBox.confirm('确认删除?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const data = {
            _gp: 'admin.advert', // 请求参数
            _mt: 'delete', // 请求参数
            type: row.type, //广告类型
            adId: row.id,//广告ID
          }
          post(data).then((res) => {
            if (200 == res.data.errno) {
              ElMessage.success('删除成功')
              this.record()
            } else {
              ElMessage.error(res.data.errmsg)
            }
          })
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作！'
          })
        })
    },
    // 清洗数据，只保留类目
    // recursion(data) {
    //   if (data == 0 || data == undefined) {
    //     return data
    //   }
    //   for (let i = 0; index < data.length; i++) {
    //     if (data[i].children.length === 0 || data[i].children[0].value.indexOf("G_") > -1
    //     ) {
    //       data[i].children = undefined;
    //     } else {
    //       data[i].children(data[i].children)

    //     }
    //   }
    //   return data
    // },


    // 弹框
    handleClose(done) {
      this.$refs.formName.resetFields();//清空表单验证
      ElMessage({
        type: 'info',
        message: '取消操作！'
      })
        ; (this.dialogVisible = false)
    },

    // 取消
    resetForm() {
      this.$refs.formName.resetFields();//清空表单验证
      ElMessage({
        type: 'info',
        message: '取消操作！'
      })
      this.dialogVisible = false
    },

    // 分页
    limitv(e) {
      this.index.limit = e
      this.record()
    },
    pagev(e) {
      this.index.page = e
      this.record()
    }
  }
}
</script>

<style lang="less" scoped>
// 输入框
.el-input {
  width: 350px;
}
</style>
